{% extends 'base_backend.html' %}
{% load static admin_static i18n %}
{% load zhongbao_admin_filtets %}
{% load config_filters %}

{% block header_tail %}
<link rel="stylesheet" href="{% static 'public/CodeMirror/lib/codemirror.css' %}">
<link rel="stylesheet" href="{% static 'public/ComboSelect/css/combo.select.css' %}">
<link rel="stylesheet" href="{% static 'public/CodeMirror/theme/lesser-dark.css' %}">
<link rel="stylesheet" href="{% static 'public/CodeMirror/addon/dialog/dialog.css' %}">
<link rel="stylesheet" href="{% static 'public/CodeMirror/addon/search/matchesonscrollbar.css' %}">
<link rel="stylesheet" href="{% static 'plugins/select2/select2.css' %}">
<link rel="stylesheet" href="{% static 'zhongbao/config/css/main.css' %}">
<style>
    .select2-container--default .select2-selection--multiple .select2-selection__choice {
        background-color: #3c8dbc;
        border-color: #3c8dbc;
    }
</style>
{% endblock header_tail %}

{% block section_content %}
<div>
    <div class="box-header with-border">
        <h3 class="box-title">修改配置</h3>
    </div>
    <!-- form start -->
    <div class="box box-primary">
        <div class="box-body">
            <form id="create_user_form" role="form" action="" method="post"
                  enctype="multipart/form-data">{% csrf_token %}

                <div style="width: 60%;height:65px;float: left;">
                    {% for i in config_show_fields %}
                    <div class="input-group" style="float: left; padding-right: 20px;width:20%">
                        <label for="" title="{{ i.title }}">{{ i.name }}：</label>
                        <div>
                            <input class="config-input" value="{{ i.field }}" disabled title="{{ i.title }}">
                        </div>
                    </div>
                    {% endfor %}
                </div>
                <div style="clear: both"></div>
                <div style="width: 100%">
                    {% for field in form %}
                    {% if field.name == 'repeat_times' %}
                    {% if perms.config.view_repeattimes %}
                    <div class="form-group" style="float: left; padding-right: 20px;width: 12%">
                        <label for="" class="control-label">{{ field.label }}：</label>
                        <p class="add-config">{{ field }}</p>
                    </div>
                    {% else %}
                    <div class="form-group select-config-div"
                         style="float: left; margin-right: 20px;display: none">
                        <label for="" class="control-label"
                               title="{{ field.help_text }}">{{ field.label }}：</label>
                        <p>{{ field }}</p>
                    </div>
                    {% endif %}
                    {% elif field.name == 'gid' %}
                    <div class="form-group"
                         style="float: left; padding-right: 20px;width: 12% ;display:{% if config.status == 1 %}none{% endif %}"
                    >
                        <label for="" class="control-label">{{ field.label }}：</label>
                        <p class="add-config">{{ field }}</p>
                    </div>
                    {% else %}
                    <div class="form-group" style="float: left; padding-right: 20px;width: 12%">
                        <label for="" class="control-label">{{ field.label }}：</label>
                        <p class="add-config">{{ field }}</p>
                    </div>
                    {% endif %}
                    {% endfor %}
                    <div class="form-group select-config-div" style="float: left; width: 30%; display: none;">
                        <p style="display: none" id="clock_time_week_json">{{ clock_time_week_json }}</p>
                        <label for="" class="control-label">定时执行：</label>
                        <p>
                            <select class=" select2" multiple="multiple" style="width: 65%" name="clock_time_week"
                                    data-placeholder="Select a State">
                                {% for option in add_week_options %}
                                <option value="{{ option.val }}">{{ option.text }}</option>
                                {% endfor %}
                            </select>
                            <input class="config-input" type="time" style="width: 20%" name="clock_time_hour"
                                   value="{{ clock_time_hour }}">
                        </p>
                    </div>
                </div>
                <br style="clear: both">
                <hr style="margin-top: 0">
                <div class="form-group">
                    <!--
                        {/% if perms.config.change_config %}
                        -->
                    {% if config.task.status.code == 2 or config.task.status.code == 5 or config.task.is_rework == 1 %}
                    <label for="">修改信息：</label><input type="text" name="change_config_message" size="50"
                                                      placeholder="请填入修改原因和概括修改内容">
                    <span class="btn btn-info btn-xs" tag="1" id="code-eidt">编辑代码</span>
                    <span class="btn btn-info btn-xs" onclick="deleteOneConfig({{ config.id }})">删除配置</span>
                    {% endif %}
                    <!--
                        {/% endif %}
                        -->
                    {% if config.config_flag != 3 %}
                    <a href="{% url 'task:change_history' config_id %}" class="btn btn-info btn-xs"
                       target="_blank">修改历史</a>
{#                    {% if user.is_superuser %}#}
{#                        <a href="#" class="btn btn-info btn-xs" data-toggle="modal" data-target="#myModal" target="_blank">一键同步</a>#}
{#                    {% endif %}#}
<!--                        <a href="#" class="btn btn-info btn-xs" onclick="Restocking({{ config.id }})">重新入库</a>-->
                    {% endif %}
                    <a href="{{ debug_url }}" class="btn btn-info btn-xs"
                       target="_blank">测试</a>
                    <span style="color: #00a7d0;margin-left: 10px"></span>
                </div>

                <div class="form-group">
                    <p style="margin-left: 10px; color: #00a7d0;" id="code-help">
                        <span style="font-weight: bold">提示：</span>
                        {% if config.task.status.code == 2 or config.task.status.code == 5 %}
                        <span style="margin-right: 10px">修改代码点击<b style="font-weight: bold">编辑代码</b>按钮； </span>
                        {% endif %}
                        <span style="margin-right: 10px">鼠标在代码框内点击后：ctrl+F 查找，ctrl+G 下一个</span>
                    </p>
                    <div id="file_show">
                        <textarea name="code" id="code" cols="100%" rows="30">{{ code }}</textarea>
                    </div>
                </div>
                {% if config.task.status.code == 2 or config.task.status.code == 5 or config.task.is_rework == 1 %}
                <p class="btn btn-primary" id="_save">修改配置</p>
                {% endif %}
                <br>

                <!--确认修改弹出框-->
                <div class="modal fade" id="cancel-window" tabindex="-1" role="dialog"
                     aria-labelledby="myModalLabel" style="top:30%">
                    <div class="modal-dialog" role="document">
                        <div class="panel panel-danger">
                            <div class="panel-heading">
                                <h3 class="panel-title">确认要修改配置吗？</h3>
                            </div>
                            <div class="modal-footer">
                                <button type="button" id="cancel_close" class="btn btn-default"
                                        data-dismiss="modal">取消
                                </button>
                                <button type="submit" id="cancel-submit" class="btn btn-default">
                                    确定
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </form>
            <input id="configIds" name="configIds" value="" style="display: none;">
            <!-- 频道编辑弹出窗口-->
            <form action="{{ channels_delete_url }}" method="post">{% csrf_token %}
                <input type="text" id="channel-change-all" name="channel-change-all" class="no-display"
                       autocomplete="off">
                <input type="text" id="channel-delete-all" name="channel-delete-all" class="no-display"
                       autocomplete="off">
                <div class="modal fade" id="config-channel-editor" tabindex="-1" role="dialog"
                     aria-labelledby="myModalLabel">
                    <div class="modal-dialog modal-lg" role="document" style="width: 80%">
                        <div class="modal-content">
                            <div class="modal-header">
                                <button type="button" class="close" data-dismiss="modal" aria-label="Close"
                                        id="close-button0"><span
                                        aria-hidden="true">×</span></button>
                                <h4 class="modal-title" id="myModalLabel">频道修改（必须点击下方-提交-按钮后才能保存修改）</h4>
                            </div>
                            <div class="modal-body" style="width: 100%">
                                <label for="">修改已添加</label>
                                <table class="table table-bordered table-striped"
                                       style="width: 100%; table-layout: fixed">
                                    <thead>
                                    <tr>
                                        <th style="width: 75%">频道url</th>
                                        <th style="width: 15%">名称</th>
                                        <th style="width: 10%">操作</th>
                                    </tr>
                                    </thead>
                                    <tbody id="channel-tbody">
                                    {% for channel in channels_org %}
                                    <tr class="channel-tr" id="{{ channel.id }}">
                                        <td class="channel-url"><span>{{ channel.channelurl }}</span>
                                            <input type="text" class="no-display"
                                                   value="{{ channel.channelurl }}" style="width: 100%"
                                                   name="channel-url-{{ channel.id }}"></td>
                                        <td class="channel-name"><span>{{ channel.channelname }}</span>
                                            <input type="text" class="no-display"
                                                   value="{{ channel.channelname }}"
                                                   name="channel-name-{{ channel.id }}">
                                        </td>
                                        <td>
                                                    <span class="btn-link channels-change" style="cursor: pointer"
                                                          tag="1">修改</span>
                                            |
                                            <span class="btn-link channels-delete" style="cursor: pointer"
                                                  tag="1">删除</span>
                                        </td>

                                    </tr>
                                    {% endfor %}
                                    </tbody>
                                </table>
                                <div class="form-group" id="channel-display">
                                    <label for="channel-config-content">增加频道-格式:频道URL#频道名称回车</label>
                                    <textarea name="channel-config-content" class="form-control"
                                              id="channel-config-content"
                                              cols="30" style="height: 200px;">{{ channels }}</textarea>
                                </div>
                            </div>
                            <div class="modal-footer">
                                <button type="submit" id="btn_submit" class="btn btn-primary">
                                    提交
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </form>

        </div>
    </div>
</div>
<!--确认删除配置弹出框-->
<div class="modal fade" id="delete-config-window" tabindex="-1" role="dialog"
     aria-labelledby="myModalLabel" style="top:30%">
    <div class="modal-dialog" role="document">
        <div class="panel panel-danger">
            <div class="panel-heading">
                <h3 class="panel-title">确认要删除配置吗？</h3>
            </div>
            <div class="modal-footer">
                <button type="button" id="cancel_delete" class="btn btn-default"
                        data-dismiss="modal">取消
                </button>
                <button id="submit-delete" class="btn btn-default" onclick="deleteConfigs()">
                    确定
                </button>
            </div>
        </div>
    </div>
</div>
{% endblock section_content %}

{% block body_js %}
{{ block.super }}
<script src="{% static 'public/CodeMirror/lib/codemirror.js' %}"></script>
<script src="{% static 'public/CodeMirror/mode/python/python.js' %}"></script>
<script src="{% static 'public/CodeMirror/addon/dialog/dialog.js' %}"></script>
<script src="{% static 'public/CodeMirror/addon/search/searchcursor.js' %}"></script>
<script src="{% static 'public/CodeMirror/addon/search/search.js' %}"></script>
<script src="{% static 'public/CodeMirror/addon/search/jump-to-line.js' %}"></script>
<script src="{% static 'public/ComboSelect/js/jquery.combo.select.js' %}"></script>
<script src="{% static 'plugins/select2/select2.full.js' %}"></script>
<script src="{% static 'zhongbao/config/js/select_pulic.js' %}"></script>
{% if user.is_superuser %}
<script>
    //    一键同步
    function synchronization() {
        $('.overlay').show();
        var conf_gid = $("#conf_group  option:selected").val();
        var webtype = $("#web_type option:selected").val();
        var conf_tid = $("#trade_type option:selected").val();
        //去重库
        var uig = $("#id_uig option:selected").val();
        //是否代理
        var agent = $("#id_is_agent option:selected").val();
        //代理地址
        var proxy_id = $("#id_proxy_addresses_id option:selected").val();
        //数据来源
        var datasourcetype = $("#id_datasourcetype option:selected").val();
        //国家
        var country = $("#id_country option:selected").val();
        //语言
        var language = $("#id_language option:selected").val();
        $.post({
            data: {
                conf_gid: conf_gid,
                webtype: webtype,
                conf_tid:conf_tid,
                uig: uig,
                agent: agent,
                proxy_id: proxy_id,
                datasourcetype: datasourcetype,
                country: country,
                language: language,
                file_name: "{{ name }}",
                webname: "{{ config.webname }}",
                domain: "{{ config.url }}",
                path: "{{ store_path }}"
            },
            url: "{% url 'task:sync_spider' %}",
            success: function (response) {
                alert(response.message);
                $('#myModal').fadeOut();
                $('.modal-backdrop').fadeOut();
            },error: function (response) {
                alert(response.message);
                $('#myModal').fadeOut();
                $('.modal-backdrop').fadeOut();
            }
        });
   };
</script>
{% endif %}
<script>
          //入库
    var cid;
    function Restocking(cid) {
        cid = cid;
        {#alert(cid)#}
         {#if (!cid) {#}
         {#   alert("请给出要删除的配置ID！");#}
         {#   return false;#}
         {# } else {#}
         {#   $.ajaxSetup({#}
         {#       data: {#}
         {#           csrfmiddlewaretoken: '{{ csrf_token }}',#}
         {#           c_id: cid#}
         {#       }#}
         {#   });#}
         {#   $.post(#}
         {#       "{% url 'task:again_Database' %}",#}
         {#       function (response) {#}
         {#           alert(response.message)#}
         {#       }#}
         {#   )#}
         {# }#}
        $.ajax({
                type: "POST",
                url: "{% url 'task:again_Database' %}",
                data:{
                    csrfmiddlewaretoken:'{{ csrf_token }}',
                    cid: cid,
                 },
                 success: function(data) {
                     alert(data.message)
                  }
         })
    }
    var body = $('body');
    body.append("<div id='DiffBox'></div>");
    var DiffBox = $('#DiffBox');
    body.append("<div id='mask'></div>");

    $(document).ready(function () {
        $.ajaxSetup({
            data: {csrfmiddlewaretoken: '{{ csrf_token }}'}
        });
        var clock_time_select2 = $(".select2").select2({});
        clock_time_select2.val(JSON.parse($('#clock_time_week_json').text())).trigger('change');
        var change_tag = 0;
        var change_config_message = $('input[name="change_config_message"]');

        var file_show = $('#file_show');
        var textarea = document.getElementById('code');
        var editor = CodeMirror.fromTextArea(textarea, {
            mode: "python",
            lineNumbers: true,
            theme: "lesser-dark",
            readOnly: true,
            extraKeys: {"Alt-F": "findPersistent"}
        });
        editor.setOption("extraKeys", {
            Tab: function (cm) {
                var spaces = new Array(cm.getOption("indentUnit") + 1).join(" ");
                cm.replaceSelection(spaces);
            }
        });
        $('#_save').click(function () {
            if (change_config_message.val().length == 0) {
                alert('修改信息为空，请确认您进行了修改，并填写修改信息。');
                return false;
            } else {
                textarea.innerHTML = editor.getValue();
                $('#cancel-window').modal();
            }
        });

        $('.chang_config_tr').hover(function () {
                var note = $(this).find('.change_diff_a');
                note.removeClass('no-display');
            }, function () {
                var note = $(this).parent().find('.change_diff_a');
                note.addClass('no-display');
            }
        );

        // 编辑代码
        $('#code-eidt').click(function () {
            var this_tag = $(this).attr('tag');
            if (this_tag == '1') {
                editor.setOption("readOnly", false);
                $(this).attr('tag', '0');
                $(this).text('完成编辑');

            } else {
                editor.setOption("readOnly", true);
                $(this).attr('tag', '1');
                $(this).text('编辑代码');
            }
        });

        // 监控输入
        {#            $('.CodeMirror').keyup(function (e) {#}
            {#                var keys = [67, 17, 70, 71];#}
            {#               // $.inArray(e.keyCode, keys) == -1 &&#}
                {#                if (editor.getOption('readOnly') == true && $.inArray(e.keyCode, keys) == -1) {#}
                    {#                    alert('当前不能编辑，请点击-编辑代码-按钮！');#}
                    {#                    return false;#}
                    {# } #}
                {# }); #}
    });

    $('.change_diff_a').click(function () {
        DiffBox.children().remove();
        var next_tr = $(this).closest('tr').next();
        if (next_tr.length == 0) {
            alert('no change')
        } else {
            var w_height = $(window).height();
            var w_width = $(window).width();
            var wrapper = $('.wrapper');
            var v1 = $(this).parent().prev().text();
            var v2 = next_tr.find('.change_version').text();
            wrapper.css('z-index', 2);
            /*重要，z-index底层对照*/
            $.post({
                data: {'v1': v1, 'v2': v2},
                url: "{% url 'task:change_diff' %}",
                success: function (data, statusText, xmlHttpRequest) {
                    $.each(data, function (index, item) {
                        var p_tag = $(document.createElement('p'));
                        p_tag.text(item);
                        DiffBox.append(p_tag);
                    });
                    $("#mask").addClass("mask").fadeIn("slow");
                    DiffBox.fadeIn("slow");
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    console.log(textStatus)
                },
                dataType: 'json'
            });
        }
        return false
    });

    var mask = $('#mask');
    mask.click(function () {
        if (DiffBox.css('display') == 'block') {
            DiffBox.fadeOut();
            mask.fadeOut();
        }
    });

    // 频道编辑弹出框
    var config_channel = $('#config-channel');
    var channel_edtitor = $('#config-channel-editor');
    var channels = $("#channel-config-content");
    config_channel.click(function () {
        channel_edtitor.modal()
    });

    // 修改频道页
    var channel_change_all = $('#channel-change-all');
    var channel_delete_all = $('#channel-delete-all');
    $('.channels-change').click(function () {
        var this_tag = $(this).attr('tag');
        var channel_tr = $(this).closest('.channel-tr');
        var channel_url = channel_tr.find('.channel-url');
        var url_span = channel_url.find('span');
        var url_input = channel_url.find('input');
        var channel_name = channel_tr.find('.channel-name');
        var name_span = channel_name.find('span');
        var name_input = channel_name.find('input');
        var delete_span = channel_tr.find('.channels-delete');
        var delete_tag = delete_span.attr('tag');

        // 清除删除操作
        var delete_vals = channel_delete_all.val();
        if (delete_tag == '0') {
            channel_delete_all.val(delete_vals.replace(',' + channel_tr.attr('id'), ''));
            delete_span.attr('tag', '1');
            delete_span.text('删除');
            url_span.removeClass('channels-delete-line');
            name_span.removeClass('channels-delete-line');
        }

        // 修改和取消修改
        var change_vals = channel_change_all.val();
        if (this_tag == '1') {
            channel_change_all.val(change_vals + ',' + channel_tr.attr('id'));
            $(this).attr('tag', '0');
            $(this).text('取消修改');
            url_span.addClass('no-display');
            url_input.removeClass('no-display');
            name_span.addClass('no-display');
            name_input.removeClass('no-display');
        } else {
            channel_change_all.val(change_vals.replace(',' + channel_tr.attr('id'), ''));
            $(this).attr('tag', '1');
            $(this).text('修改');
            url_span.removeClass('no-display');
            url_input.addClass('no-display');
            url_input.val(url_span.text());
            name_span.removeClass('no-display');
            name_input.addClass('no-display');
            name_input.val(name_span.text());
        }
    });

    // 删除频道
    $('.channels-delete').click(function () {
        var this_tag = $(this).attr('tag');
        var channel_tr = $(this).closest('.channel-tr');
        var channel_url = channel_tr.find('.channel-url');
        var url_input = channel_url.find('input');
        var url_span = channel_url.find('span');
        var channel_name = channel_tr.find('.channel-name');
        var name_span = channel_name.find('span');
        var name_input = channel_name.find('input');
        var change_span = channel_tr.find('.channels-change');
        var change_tag = change_span.attr('tag');

        // 清除修改操作
        var change_vals = channel_change_all.val();
        if (change_tag == '0') {
            channel_change_all.val(change_vals.replace(',' + channel_tr.attr('id'), ''));
            change_span.attr('tag', '1');
            change_span.text('修改');
            url_span.removeClass('no-display');
            url_input.addClass('no-display');
            url_input.val(url_span.text());
            name_span.removeClass('no-display');
            name_input.addClass('no-display');
            name_input.val(name_span.text());
        }

        // 删除和取消删除
        var delete_vals = channel_delete_all.val();
        if (this_tag == '1') {
            channel_delete_all.val(delete_vals + ',' + channel_tr.attr('id'));
            $(this).attr('tag', '0');
            $(this).text('取消删除');
            url_span.addClass('channels-delete-line');
            name_span.addClass('channels-delete-line');
        } else {
            channel_delete_all.val(delete_vals.replace(',' + channel_tr.attr('id'), ''));
            $(this).attr('tag', '1');
            $(this).text('删除');
            url_span.removeClass('channels-delete-line');
            name_span.removeClass('channels-delete-line');
        }

    });

    // 关闭频道编辑提醒
    $('#close-button0').click(function () {
        alert('请确认您的修改已经提交，不然无法保存！')
    });
    var cids;

    function deleteOneConfig(cid) {
        //$("#configIds").val(cid);
        cids = cid;
        $("#delete-config-window").modal();
    }

    function deleteConfigs() {
        if (!cids) {
            alert("请给出要删除的配置ID！");
            return false;
        } else {
            $.ajaxSetup({
                data: {
                    csrfmiddlewaretoken: '{{ csrf_token }}',
                    cids: cids
                }
            });
            $.post(
                "{% url 'task:delete_config' %}",
                function (response) {
                    cids = null;
                    window.location.href = '{{ reverse_url }}';
                }
            )
        }
    }
</script>
{% endblock body_js %}